<template>
  <div class="problem-detail">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <i class="fas fa-arrow-left"></i>
      <span>返回题目列表</span>
    </div>

    <!-- 左侧题目详情 -->
    <div class="problem-info panel">
      <div class="problem-header">
        <h1 class="problem-title">{{ problem.title }}</h1>
        <div class="problem-meta">
          <span :class="['difficulty-tag', problem.difficulty.toLowerCase()]">
            <i class="fas" :class="{
              'fa-circle': true,
              'easy-icon': problem.difficulty.toLowerCase() === 'easy',
              'medium-icon': problem.difficulty.toLowerCase() === 'medium',
              'hard-icon': problem.difficulty.toLowerCase() === 'hard'
            }"></i>
            {{ getDifficultyText(problem.difficulty) }}
          </span>
          <span class="meta-item">
            <i class="fas fa-code"></i> {{ problem.submissionCount }} 次提交
          </span>
          <span class="meta-item">
            <i class="fas fa-check"></i> {{ problem.acceptanceRate }}% 通过率
          </span>
          <button class="history-btn" @click="showSubmissionHistory">
            <i class="fas fa-history"></i> 提交历史
          </button>
        </div>
      </div>
      
      <div class="problem-content" v-html="problem.content"></div>
      
      <!-- 1. 在题目示例区域添加测试用例格式提示 -->
      <div class="section">
        <h3>示例</h3>
        <div class="test-case-format-info">
          <i class="fas fa-info-circle"></i>
          <p>注意：输入中的数值应使用<strong>空格分隔</strong>，不要使用逗号。系统使用多测试用例格式，<strong>第一行的数字表示测试用例数量</strong>，您的代码需要先读取这个数量。</p>
        </div>
        <div class="example-list">
          <div 
            v-for="(example, index) in problem.examples" 
            :key="index"
            class="example-item"
          >
            <h3>示例 {{ index + 1 }}</h3>
            <div class="example-box">
              <strong>输入：</strong>
              <pre>{{ example.input }}</pre>
            </div>
            <div class="example-box">
              <strong>输出：</strong>
              <pre>{{ example.output }}</pre>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间代码编辑区 -->
    <div class="code-editor panel" :class="{'has-result': showResult}">
      <div class="editor-header">
        <div class="language-select">
          <select v-model="selectedLanguage" @change="changeLanguage">
            <option v-for="lang in languages" :key="lang.id" :value="lang.id">
              {{ lang.name }}
            </option>
          </select>
        </div>
        <div class="editor-actions">
          <button class="run-btn" @click="runCode" :disabled="isExecuting">
            <i class="fas" :class="isExecuting ? 'fa-spinner fa-spin' : 'fa-play'"></i> 
            {{ isExecuting ? '执行中...' : '运行' }}
          </button>
          <button class="submit-btn" @click="submitCode" :disabled="isExecuting">
            <i class="fas" :class="isExecuting ? 'fa-spinner fa-spin' : 'fa-paper-plane'"></i>
            {{ isExecuting ? '提交中...' : '提交' }}
          </button>
        </div>
      </div>
      
      <!-- 测试用例提示区域 -->
      <div class="testcase-tip">
        <div class="tip-icon"><i class="fas fa-info-circle"></i></div>
        <div class="tip-content">
          <p><strong>多测试用例格式说明：</strong></p>
          <p>系统使用多测试用例评测，输入格式如下：</p>
          <ul>
            <li>第一行是测试用例数量n（<strong>系统会自动添加，示例中未显示</strong>）</li>
            <li>接下来的n行是各个测试用例的输入</li>
          </ul>
          <p>请确保您的代码先读取测试用例数量，然后循环处理每个测试用例。</p>
        </div>
      </div>
      
      <textarea ref="codeEditor"></textarea>
      
      <div class="run-result" v-if="showResult">
        <div class="result-header">
          <span>
            <i class="fas" :class="{
              'fa-spinner fa-spin': resultStatus === 'loading',
              'fa-check-circle': resultStatus === 'success',
              'fa-exclamation-circle': resultStatus === 'error'
            }"></i>
            {{ resultStatus === 'loading' ? '正在执行...' : (resultStatus === 'success' ? '执行成功' : '执行失败') }}
          </span>
          <button class="close-btn" @click="showResult = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div :class="['result-content', resultStatus]">
          <pre>{{ runResult }}</pre>
        </div>
        <div class="resize-handle" @mousedown="startResize"></div>
      </div>
    </div>

    <!-- 右侧 AI 助手 -->
    <div class="ai-assistant panel" :class="{ collapsed: isAiCollapsed }">
      <div class="ai-header">
        <h2>AI 助手</h2>
        <button class="collapse-btn" @click="toggleAi">
          <i :class="['fas', isAiCollapsed ? 'fa-expand' : 'fa-compress']"></i>
        </button>
      </div>
      
      <div class="ai-content" v-show="!isAiCollapsed">
        <div class="quick-actions">
          <button @click="askAi('hint')" class="action-btn hint">
            <i class="fas fa-lightbulb"></i> 获取提示
          </button>
          <button @click="askAi('approach')" class="action-btn approach">
            <i class="fas fa-compass"></i> 解题思路
          </button>
          <button @click="askAi('complexity')" class="action-btn complexity">
            <i class="fas fa-chart-line"></i> 复杂度分析
          </button>
          <button @click="askAi('optimize')" class="action-btn optimize">
            <i class="fas fa-rocket"></i> 代码优化
          </button>
        </div>
        
        <div class="chat-container" ref="chatContainer">
          <div v-for="(message, index) in chatHistory" :key="index" 
               :class="['chat-message', message.role, { 'is-loading': message.isLoading, 'error': message.error }]">
            <div class="message-content">
              <div v-if="message.role === 'ai'" class="ai-avatar">AI</div>
              <div v-if="message.role === 'user'">{{ message.content }}</div>
              <div v-else v-html="parseMarkdown(message.content)"></div>
            </div>
          </div>
        </div>
        
        <div class="chat-input">
          <input 
            type="text" 
            v-model="userInput" 
            placeholder="输入问题..."
          >
          <button class="send-btn" @click="sendMessage" :disabled="isAiTyping">
            <i class="fas fa-paper-plane"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 提交历史弹窗 -->
    <div class="submission-history-modal" v-if="showHistoryModal">
      <div class="modal-overlay" @click="closeHistoryModal"></div>
      <div class="modal-container">
        <div class="modal-header">
          <h3>提交历史记录</h3>
          <button class="close-modal-btn" @click="closeHistoryModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div v-if="isHistoryLoading" class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i> 加载中...
          </div>
          <div v-else-if="historyError" class="history-error">
            <i class="fas fa-exclamation-circle"></i> {{ historyError }}
          </div>
          <div v-else-if="submissions.length === 0" class="no-history">
            <i class="fas fa-info-circle"></i> 暂无提交记录
          </div>
          <div v-else class="submission-table-container">
            <table class="submission-table">
              <thead>
                <tr>
                  <th>状态</th>
                  <th>语言</th>
                  <th>执行时间</th>
                  <th>内存</th>
                  <th>提交时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(submission, index) in submissions" :key="index" @click="showSubmissionDetail(submission)">
                  <td :class="['status', getStatusClass(submission.status)]">{{ submission.status }}</td>
                  <td>{{ getLanguageName(submission.language_id) }}</td>
                  <td>{{ submission.execution_time || '-' }} ms</td>
                  <td>{{ submission.memory_used || '-' }} KB</td>
                  <td>{{ formatDate(submission.created_at) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交详情弹窗 -->
    <div class="submission-detail-modal" v-if="showDetailModal">
      <div class="modal-overlay" @click="closeDetailModal"></div>
      <div class="modal-container">
        <div class="modal-header">
          <h3>提交详情</h3>
          <button class="close-modal-btn" @click="closeDetailModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="submission-info">
            <div class="info-row">
              <span class="label">状态:</span>
              <span :class="['status', getStatusClass(selectedSubmission.status)]">{{ selectedSubmission.status }}</span>
            </div>
            <div class="info-row">
              <span class="label">语言:</span>
              <span>{{ getLanguageName(selectedSubmission.language_id) }}</span>
            </div>
            <div class="info-row">
              <span class="label">执行时间:</span>
              <span>{{ selectedSubmission.execution_time || '-' }} ms</span>
            </div>
            <div class="info-row">
              <span class="label">内存消耗:</span>
              <span>{{ selectedSubmission.memory_used || '-' }} KB</span>
            </div>
            <div class="info-row">
              <span class="label">提交时间:</span>
              <span>{{ formatDate(selectedSubmission.created_at) }}</span>
            </div>
          </div>
          <div class="submission-code">
            <h4>提交的代码:</h4>
            <pre><code>{{ selectedSubmission.source_code }}</code></pre>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css'
// 语言支持
import 'codemirror/mode/javascript/javascript'
import 'codemirror/mode/python/python'
import 'codemirror/mode/clike/clike'
// 代码编辑器增强
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/edit/closebrackets'
import 'codemirror/addon/selection/active-line'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/javascript-hint'
import { baseURL } from '@/utils/api'
// 导入markdown解析库
import MarkdownIt from 'markdown-it'
// 导入KaTeX支持
import mk from 'markdown-it-katex'
import 'katex/dist/katex.min.css'
import axios from 'axios'
// 导入代码模板
import { codeTemplates } from '@/assets/templates/codeTemplates'

export default {
  name: 'ProblemDetailView',
  data() {
    return {
      problem: {
        title: '加载中...',
        difficulty: 'medium',
        submissionCount: 0,
        acceptanceRate: 0,
        content: '<div>正在加载题目内容...</div>',
        examples: []
      },
      selectedLanguage: null, // 不再预设默认语言
      editor: null,
      showResult: false,
      runResult: '',
      resultStatus: 'success',
      isAiCollapsed: true, // 默认收起AI助手
      userInput: '',
      chatHistory: [],
      languages: [], // 存储支持的语言列表
      languagesModeMap: {}, // 将在获取语言后动态构建
      isLoading: true,
      errorMessage: '',
      testCase: null,
      isExecuting: false,
      isAiTyping: false, // 标记AI是否正在回复中
      // 初始化markdown解析器
      md: new MarkdownIt({
        html: false,       // 禁用HTML标签
        breaks: true,      // 将换行符转换为<br>
        linkify: true,     // 自动转换URL到链接
        typographer: true,  // 启用一些语言中性的替换和引号美化
        headerPrefix: '',  // 不添加前缀到标题id
        maxNesting: 10     // 允许更高级别的嵌套
      }).use(mk), // 使用KaTeX插件
      
      // 提交历史相关数据
      showHistoryModal: false,
      isHistoryLoading: false,
      historyError: '',
      submissions: [],
      
      // 提交详情相关数据
      showDetailModal: false,
      selectedSubmission: {},
      
      // 添加拖拽相关数据
      isResizing: false,
      initialHeight: 0,
      initialMouseY: 0,
      resultHeight: 200  // 默认高度
    }
  },
  mounted() {
    this.initCodeMirror()
  },
  created() {
    // 获取题目ID并加载题目数据
    const problemId = this.$route.params.id
    if (problemId) {
      this.fetchProblemDetail(problemId)
    } else {
      this.errorMessage = '未找到题目ID'
      console.error('未找到题目ID')
    }
    
    // 获取支持的语言列表
    this.fetchLanguages()
  },
  beforeDestroy() {
    // 清理编辑器实例
    if (this.editor) {
      this.editor.toTextArea()
    }
  },
  methods: {
    // 安全的Base64编码函数 - 支持Unicode
    safeBase64Encode(str) {
      if (!str) return '';
      try {
        // 规范化换行符为统一格式
        const normalizedStr = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
        return btoa(unescape(encodeURIComponent(normalizedStr)));
      } catch (e) {
        console.error('Base64编码失败:', e, str);
        // 如果字符串特别长，尝试分段编码
        try {
          const chunks = [];
          for (let i = 0; i < str.length; i += 1000) {
            const chunk = str.slice(i, i + 1000);
            chunks.push(btoa(unescape(encodeURIComponent(chunk))));
          }
          return chunks.join('');
        } catch (e2) {
          console.error('分段Base64编码也失败:', e2);
          return btoa('编码失败'); // 兜底返回
        }
      }
    },
    
    // 安全的Base64解码函数 - 支持Unicode
    safeBase64Decode(str) {
      if (!str) return '';
      try {
        return decodeURIComponent(escape(atob(str)));
      } catch (e) {
        console.error('Base64解码失败:', e, str);
        try {
          // 尝试直接解码，可能丢失一些UTF-8字符但至少提供一些信息
          return atob(str);
        } catch (e2) {
          console.error('简单Base64解码也失败:', e2);
          return '解码失败'; // 兜底返回
        }
      }
    },
    
    async fetchProblemDetail(problemId) {
      this.isLoading = true
      try {
        // 构建API URL
        const url = `${baseURL}/CodeQuestion-service/problems/getProblemById/${problemId}`
        
        const response = await fetch(url)
        if (!response.ok) {
          throw new Error('网络请求失败')
        }
        
        const data = await response.json()
        console.log('获取题目详情返回数据:', data)
        
        if (data.result === 'success' && data.problem) {
          // 将题目数据赋值给组件状态
          this.problem = {
            id: data.problem.id,
            title: data.problem.title || '未命名题目',
            difficulty: data.problem.difficulty || 'MEDIUM',
            content: data.problem.description || '<div>题目描述加载失败</div>',
            submissionCount: data.problem.submissionCount || 0, // 使用后端返回的提交次数
            acceptanceRate: data.problem.acceptanceRate || 0,   // 使用后端返回的通过率
            hasLimits: data.problem.has_limits,
            timeLimit: data.problem.time_limit,
            memoryLimit: data.problem.memory_limit,
            examples: []
          }
          
          // 保存原始测试用例数据用于代码验证
          this.testCase = data.testCase || null;
          
          // 如果有测试用例数据，解析示例
          if (data.testCase && data.testCase.example_json) {
            try {
              const examples = JSON.parse(data.testCase.example_json)
              this.problem.examples = examples.map(ex => {
                let input = ex.input || '';
                let output = ex.expectedOutput || '';
                
                // 确保示例输入格式完整，不需要用户自己添加测试用例数量
                if (input && !input.trim().match(/^\d+\s*\n/)) {
                  // 如果输入不是以数字开头后跟换行，说明没有测试用例数量标记
                  // 此时假设这是单个测试用例
                  input = "1\n" + input;
                }
                
                // 处理输入，为显示目的移除第一行的测试用例数量
                let displayInput = input;
                const inputLines = input.split('\n');
                if (inputLines.length > 1 && /^\d+$/.test(inputLines[0].trim())) {
                  // 如果第一行是纯数字（测试用例数量），则仅显示后续行
                  displayInput = inputLines.slice(1).join('\n');
                }
                
                return {
                  input: displayInput, // 显示时不包含测试用例数量
                  rawInput: input,     // 保存原始输入（包含测试用例数量）
                  output: output
                }
              });
            } catch (e) {
              console.error('解析示例数据失败:', e)
              this.problem.examples = []
            }
          }
          
          // 清空编辑器内容
          if (this.editor) {
            this.editor.setValue('');
          }
          
          // 加载语言后，根据题目类型自动选择适当的模板
          if (this.languages.length > 0) {
            // 寻找C语言（langId 49对应GCC）
            const cLang = this.languages.find(l => l.id === 49);
            if (cLang) {
              this.selectedLanguage = 49; // 默认选C语言
            } else {
              this.selectedLanguage = this.languages[0].id;
            }
            // 更新编辑器语言模式
            this.changeLanguage();
          }
          
        } else {
          throw new Error(data.message || '获取题目详情失败')
        }
      } catch (error) {
        this.errorMessage = `加载题目失败: ${error.message}`
        console.error('获取题目详情失败:', error)
      } finally {
        this.isLoading = false
      }
    },
    getDifficultyText(difficulty) {
      return {
        EASY: '简单',
        MEDIUM: '中等',
        HARD: '困难',
        easy: '简单',
        medium: '中等',
        hard: '困难'
      }[difficulty] || ''
    },
    goBack() {
      this.$router.push('/problems')
    },
    initCodeMirror() {
      this.editor = CodeMirror.fromTextArea(this.$refs.codeEditor, {
        mode: 'text/plain', // 初始时使用纯文本模式
        theme: 'default',
        lineNumbers: true,
        line: true,
        matchBrackets: true,
        autoCloseBrackets: true,
        styleActiveLine: true,
        tabSize: 2,
        indentUnit: 2,
        indentWithTabs: false,
        extraKeys: {
          'Ctrl-Space': 'autocomplete'
        }
      })

      // 初始化时不设置默认代码，等待语言选择后再设置
      this.editor.setValue('')

      // 自动调整高度
      this.editor.setSize('100%', '100%')
    },
    changeLanguage() {
      if (!this.selectedLanguage || !this.editor) return
      
      // 获取选中语言对应的编辑器模式
      const mode = this.getLanguageMode(this.selectedLanguage)
      
      // 设置编辑器的语言模式
      this.editor.setOption('mode', mode)
      
      // 获取当前代码
      const currentCode = this.editor.getValue()
      
      // 如果编辑器中没有代码，则设置初始模板
      if (!currentCode.trim()) {
        // 获取选中的语言信息
        const language = this.languages.find(l => l.id === this.selectedLanguage)
        const langName = language ? language.name.toLowerCase() : ''
        
        // 获取语言模板
        const templateCode = this.getLanguageTemplate(langName)
        
        // 设置代码模板
        if (templateCode) {
          this.editor.setValue(templateCode)
        } else {
          this.editor.setValue('')
        }
      }
    },
    runCode() {
      const code = this.editor.getValue()
      if (!code.trim()) {
        this.showResult = true
        this.resultStatus = 'error'
        this.runResult = '代码不能为空'
        return
      }
      
      this.executeCode(code, true)
    },
    submitCode() {
      const code = this.editor.getValue()
      if (!code.trim()) {
        this.showResult = true
        this.resultStatus = 'error'
        this.runResult = '代码不能为空'
        return
      }
      
      this.executeCode(code, false)
    },
    async executeCode(code, isRunOnly) {
      // 显示结果区域并设置为加载状态
      this.showResult = true
      this.resultStatus = 'loading'
      this.runResult = '代码执行中...'
      this.isExecuting = true
      
      try {
        // 检查是否有代码
        if (!code || !code.trim()) {
          this.resultStatus = 'error'
          this.runResult = '代码不能为空'
          this.isExecuting = false
          return
        }
        
        // 对于C语言代码，检查是否包含过多的提示文字
        const language = this.languages.find(l => l.id === this.selectedLanguage);
        const langName = language ? language.name.toLowerCase() : '';
        
        if (langName.includes('c') && !langName.includes('c++') && !langName.includes('c#') && 
            code.includes('printf') && (code.includes('请输入') || code.includes('两数之和为'))) {
          console.log('检测到C语言代码中包含不必要的提示文字，可能导致测试不通过');
          // 不中断执行，只记录日志
        }
        
        // 使用选择的语言ID
        const languageId = this.selectedLanguage
        
        // 根据运行模式选择不同的输入
        let stdin = ''
        if (isRunOnly && this.problem.examples.length > 0) {
          // 运行模式：使用第一个示例的输入（使用包含测试用例数量的原始输入）
          stdin = this.problem.examples[0].rawInput || this.problem.examples[0].input || ''
          console.log('使用示例输入:', stdin)
        } else if (!isRunOnly && this.testCase) {
          // 提交模式：使用测试用例的输入
          stdin = this.testCase.judge_stdin || ''
          console.log('使用judge_stdin:', stdin)
        }
        
        // 去除输入中可能存在的多余空格
        stdin = stdin.trim()
        
        console.log('原始代码:', code);
        console.log('原始输入:', stdin);
        
        // 不再对代码和输入进行base64编码，直接使用原始文本
        const submissionData = {
          language_id: languageId,
          source_code: code,         // 直接使用原始代码
          stdin: stdin,              // 直接使用原始输入
          base64_encoded: false,     // 指明未使用base64编码
          // 增加等待时间和超时设置
          wait: true,
          cpu_time_limit: 5,  // 设置更高的CPU时间限制（秒）
          memory_limit: 512000 // 设置更高的内存限制（KB）
        }
        
        console.log('向Judge0提交的数据:', submissionData)
        
        // 调用Judge0 API - 使用与TestView相同的API地址
        const judge0Url = `http://39.106.42.243:2358/submissions?timestamp=${new Date().getTime()}`
        const response = await fetch(judge0Url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(submissionData)
        })
        
        if (!response.ok) {
          console.error('提交代码请求失败:', response.status, response.statusText)
          throw new Error(`提交代码失败: ${response.status} ${response.statusText}`)
        }
        
        const submission = await response.json()
        console.log('Judge0提交响应:', submission)
        
        if (!submission.token) {
          throw new Error('未获得有效的提交令牌')
        }
        
        // 轮询获取执行结果
        const resultResponse = await this.pollSubmissionResult(submission.token)
        
        if (!resultResponse || !resultResponse.status) {
          throw new Error('未获得有效的执行结果')
        }
        
        // 处理执行结果
        if (resultResponse.status.id > 4) {
          // 执行出错
          this.resultStatus = 'error'
          let errorMessage = this.formatJudge0Error(resultResponse.status, resultResponse.stderr, resultResponse.compile_output)
          this.runResult = errorMessage
          
          if (!isRunOnly) {
            // 保存提交记录
            await this.saveSubmission({
              status: 'Error',
              execution_time: resultResponse.time,
              memory_used: resultResponse.memory,
              source_code: code
            });
          }
        } else {
          // 执行成功
          let output = resultResponse.stdout || ''
          // 确保输出中没有不必要的空白字符
          output = output.trim()
          console.log('输出:', output)
          
          if (isRunOnly) {
            // 运行模式：直接显示输出
            this.resultStatus = 'success'
            this.runResult = output
          } else {
            // 提交模式：对比输出与期望输出
            let expectedOutput = this.testCase.judge_expected_output || ''
            // 确保期望输出中没有不必要的空白字符
            expectedOutput = expectedOutput.trim()
            console.log('期望输出:', expectedOutput)
            
            // 对比前再做一次规范化：移除所有空白字符后比较
            const normalizedOutput = output.replace(/\s+/g, '')
            const normalizedExpected = expectedOutput.replace(/\s+/g, '')
            console.log('规范化后的输出:', normalizedOutput)
            console.log('规范化后的期望输出:', normalizedExpected)
            
            // 使用严格相等来比较处理后的字符串
            if (normalizedOutput === normalizedExpected) {
              this.resultStatus = 'success'
              this.runResult = '恭喜！所有测试用例通过。\n\n输出:\n' + output
              
              // 保存提交记录
              await this.saveSubmission({
                status: 'Accepted',
                execution_time: resultResponse.time,
                memory_used: resultResponse.memory,
                source_code: code
              });
            } else {
              this.resultStatus = 'error'
              this.runResult = `测试未通过。\n\n您的输出:\n${output}\n\n期望输出:\n${expectedOutput}`
              
              // 保存提交记录
              await this.saveSubmission({
                status: 'Wrong Answer',
                execution_time: resultResponse.time,
                memory_used: resultResponse.memory,
                source_code: code
              });
            }
          }
        }
      } catch (error) {
        console.error('代码执行错误:', error)
        this.resultStatus = 'error'
        this.runResult = '代码执行失败: ' + error.message
      } finally {
        this.isExecuting = false
      }
    },
    
    async pollSubmissionResult(token, retries = 20, interval = 2000) {
      // 轮询获取Judge0执行结果 - 使用与TestView相同的API地址
      const judge0TokenUrl = `http://39.106.42.243:2358/submissions/${token}?base64_encoded=false`
      
      for (let i = 0; i < retries; i++) {
        try {
          console.log(`第${i+1}次尝试获取执行结果...`)
          const response = await fetch(judge0TokenUrl)
          
          // 即使状态码不是200，也尝试解析响应
          const result = await response.json().catch(e => {
            console.error(`解析轮询响应失败:`, e)
            return {} // 返回空对象以便后续检查
          })
          
          console.log(`轮询结果 #${i+1}:`, result)
          
          // 检查是否有状态信息
          if (result.status) {
            // 如果状态ID等于3或更高，表示执行已经完成
            if (result.status.id >= 3) {
              return result
            }
          }
          
          // 等待指定时间后再次轮询
          await new Promise(resolve => setTimeout(resolve, interval))
        } catch (error) {
          console.error(`第${i+1}次轮询出错:`, error)
          
          // 出错后稍微等待一下再继续尝试
          await new Promise(resolve => setTimeout(resolve, interval))
          
          // 不立即抛出错误，继续下一次轮询
          continue
        }
      }
      
      throw new Error('执行超时或无法获取结果，请稍后再试')
    },
    toggleAi() {
      this.isAiCollapsed = !this.isAiCollapsed
    },
    askAi(type) {
      const questions = {
        hint: '能给我一些解题提示吗？',
        approach: '这道题有哪些解题思路？',
        complexity: '请分析一下这道题的时间和空间复杂度。',
        optimize: '有什么优化建议吗？'
      }
      this.sendMessage(questions[type])
    },
    sendMessage(message) {
      if (typeof message === 'string') {
        this.userInput = message
      }
      if (!this.userInput.trim()) return
      
      // 添加用户消息
      this.chatHistory.push({
        role: 'user',
        content: this.userInput
      })
      
      // 获取当前问题上下文
      const selectedLang = this.languages.find(l => l.id === this.selectedLanguage)
      const context = {
        problem: {
          title: this.problem.title,
          difficulty: this.problem.difficulty,
          content: this.problem.content,
          examples: this.problem.examples
        },
        code: this.editor ? this.editor.getValue() : '',
        language: selectedLang ? selectedLang.name : '未知语言',
        question: this.userInput
      }
      
      const userQuestion = this.userInput
      this.userInput = ''
      
      // 添加AI正在输入的消息
      this.chatHistory.push({
        role: 'ai',
        content: '', // 初始为空，将通过流式API逐步填充
        isLoading: true // 标记为加载中状态
      })
      
      // 滚动到底部
      this.$nextTick(() => {
        if (this.$refs.chatContainer) {
          this.$refs.chatContainer.scrollTop = this.$refs.chatContainer.scrollHeight
        }
      })
      
      // 构建完整的消息内容，包括问题和上下文
      const enhancedQuestion = `我正在解决一道算法题：${this.problem.title}，难度：${this.getDifficultyText(this.problem.difficulty)}。
题目内容：${this.stripHtml(this.problem.content)}
${this.problem.examples.length > 0 ? `示例：
输入：${this.problem.examples[0].input}
输出：${this.problem.examples[0].output}` : ''}
使用的编程语言：${selectedLang ? selectedLang.name : '未知语言'}
${this.editor && this.editor.getValue().trim() ? `我目前的代码是：
\`\`\`
${this.editor.getValue()}
\`\`\`
` : ''}
我的问题是：${userQuestion}
请给我简洁但有帮助的回答。`
      
      // 使用 EventSource 而不是 POST 请求
      this.isAiTyping = true
      
      try {
        // 找到最后一条AI消息的索引
        const aiMessageIndex = this.chatHistory.length - 1
        
        // 使用与content.js相同的URL格式和协议
        const apiUrl = `${baseURL}/ai-service/AI/stream-chat?question=${encodeURIComponent(enhancedQuestion)}`;
        console.log('连接到EventSource:', apiUrl);
        
        // 创建EventSource连接
        const eventSource = new EventSource(apiUrl);
        let responseText = '';
        
        // 监听消息事件
        eventSource.onmessage = (event) => {
          try {
            console.log('接收到消息:', event.data);
            
            if (event.data === "[DONE]") {
              console.log('收到结束标记');
              eventSource.close();
              this.isAiTyping = false;
              this.chatHistory[aiMessageIndex].isLoading = false;
              return;
            }
            
            // 直接使用event.data作为内容，不进行JSON解析
            responseText += event.data;
            
            // 更新AI回复内容
            this.chatHistory[aiMessageIndex].content = responseText;
            this.chatHistory[aiMessageIndex].isLoading = false;
            
            // 滚动到底部
            this.$nextTick(() => {
              if (this.$refs.chatContainer) {
                this.$refs.chatContainer.scrollTop = this.$refs.chatContainer.scrollHeight;
              }
            });
          } catch (error) {
            console.error('处理消息错误:', error);
            eventSource.close();
            this.isAiTyping = false;
            this.chatHistory[aiMessageIndex].isLoading = false;
            this.chatHistory[aiMessageIndex].error = true;
            this.chatHistory[aiMessageIndex].content = '消息处理出错，请重试。';
          }
        };
        
        // 监听错误事件
        eventSource.onerror = (error) => {
          console.error('SSE错误:', error);
          eventSource.close();
          this.isAiTyping = false;
          
          if (this.chatHistory[aiMessageIndex].isLoading) {
            this.chatHistory[aiMessageIndex].isLoading = false;
            this.chatHistory[aiMessageIndex].error = true;
            this.chatHistory[aiMessageIndex].content = '连接出错，请重试。';
          }
        };
        
      } catch (error) {
        console.error('创建EventSource失败:', error);
        
        // 添加错误消息
        this.chatHistory.push({
          role: 'ai',
          content: '连接AI服务失败，请稍后重试。',
          error: true
        });
        
        this.isAiTyping = false;
      }
    },
    
    // 去除HTML标签的辅助方法
    stripHtml(html) {
      const temp = document.createElement('div')
      temp.innerHTML = html
      return temp.textContent || temp.innerText || ''
    },
    
    // 解析Markdown格式的文本
    parseMarkdown(text) {
      if (!text) return ''
      try {
        // 确保标题格式正确，在#后添加空格（如果没有）
        const formattedText = text.replace(/^(#{1,6})([^#\s])/gm, '$1 $2');
        
        // 预处理代码块，保留代码中的空格和格式
        // 查找所有可能的代码部分，如include、void、int等关键字连在一起的情况
        const processedText = formattedText
          // 处理常见C/C++代码结构
          .replace(/(\b)(include)(<)/g, '$1#include<') // 修复#include
          .replace(/(\b)(void|int|char|float|double|long|unsigned|signed|const|static|struct|enum|typedef)(\w+)/g, '$1$2 $3') // 在类型和标识符之间添加空格
          .replace(/(\w+)(\()/g, '$1 $2') // 在函数名和括号之间添加空格
          .replace(/;(\w+)/g, '; $1') // 在分号和下一个标识符之间添加空格
          .replace(/\{(\w+)/g, '{ $1') // 在左花括号和下一个标识符之间添加空格
          .replace(/\}(\w+)/g, '} $1') // 在右花括号和下一个标识符之间添加空格
          .replace(/(\))(\w+)/g, '$1 $2') // 在右括号和下一个标识符之间添加空格
          .replace(/(\w+)(=)(\w+)/g, '$1 $2 $3') // 在赋值操作符周围添加空格
          .replace(/(\w+)(>|<|>=|<=|==|!=)(\w+)/g, '$1 $2 $3') // 在比较操作符周围添加空格
          .replace(/(\w+)(\+|\-|\*|\/|%|\+=|\-=|\*=|\/=|%=)(\w+)/g, '$1 $2 $3'); // 在算术操作符周围添加空格
        
        return this.md.render(processedText)
      } catch (error) {
        console.error('Markdown解析错误:', error)
        return text
      }
    },
    async fetchLanguages() {
      try {
        // 使用与TestView相同的API地址
        const response = await fetch('http://39.106.42.243:2358/languages')
        if (!response.ok) {
          throw new Error('获取语言列表失败')
        }
        
        const data = await response.json()
        console.log('获取到的语言列表:', data)
        
        // 设置语言列表
        this.languages = data
        
        // 初始化语言模式映射
        this.buildLanguageModeMap(data)
        
        // 如果列表不为空且尚未设置选择的语言，则默认选择第一个
        if (data.length > 0) {
          this.selectedLanguage = data[0].id
          // 更新编辑器模式
          if (this.editor) {
            this.changeLanguage()
          }
        }
      } catch (error) {
        console.error('获取语言列表失败:', error)
        // 使用最小化的默认列表
        const fallbackLanguages = [
          { id: 63, name: 'JavaScript (Node.js)' }
        ]
        this.languages = fallbackLanguages
        this.buildLanguageModeMap(fallbackLanguages)
        this.selectedLanguage = 63
      }
    },
    
    // 构建语言ID到编辑器模式的映射
    buildLanguageModeMap(languages) {
      const modeMap = {}
      
      languages.forEach(lang => {
        const name = lang.name.toLowerCase()
        if (name.includes('javascript') || name.includes('node.js')) {
          modeMap[lang.id] = 'javascript'
        } else if (name.includes('python')) {
          modeMap[lang.id] = 'python'
        } else if (name.includes('java') && !name.includes('javascript')) {
          modeMap[lang.id] = 'text/x-java'
        } else if (name.includes('c++') || name.includes('cpp')) {
          modeMap[lang.id] = 'text/x-c++src'
        } else if (name.includes('c#')) {
          modeMap[lang.id] = 'text/x-csharp'
        } else if (name.includes('php')) {
          modeMap[lang.id] = 'php'
        } else if (name.includes('ruby')) {
          modeMap[lang.id] = 'ruby'
        } else if (name.includes('swift')) {
          modeMap[lang.id] = 'swift'
        } else if (name.includes('go')) {
          modeMap[lang.id] = 'go'
        } else if (name.includes('rust')) {
          modeMap[lang.id] = 'rust'
        } else {
          // 默认当作纯文本
          modeMap[lang.id] = 'text/plain'
        }
      })
      
      this.languagesModeMap = modeMap
    },
    
    // 获取语言对应的编辑器模式
    getLanguageMode(langId) {
      return this.languagesModeMap[langId] || 'text/plain'
    },
    
    // 获取特定语言的多测试用例模板
    getLanguageTemplate(langName) {
      if (langName.includes('c') && !langName.includes('c#') && !langName.includes('c++')) {
        return codeTemplates.c;
      } 
      else if (langName.includes('c++')) {
        return codeTemplates.cpp;
      } 
      else if (langName.includes('java')) {
        return codeTemplates.java;
      } 
      else if (langName.includes('python')) {
        return codeTemplates.python;
      } 
      else if (langName.includes('javascript') || langName.includes('node')) {
        return codeTemplates.javascript;
      }
      else if (langName.includes('ruby')) {
        return codeTemplates.ruby;
      }
      else if (langName.includes('php')) {
        return codeTemplates.php;
      }
      else if (langName.includes('rust')) {
        return codeTemplates.rust;
      }
      else if (langName.includes('go')) {
        return codeTemplates.go;
      }
      // 如果没有匹配的模板，返回空字符串
      return '';
    },
    
    // 新增保存提交记录的方法
    async saveSubmission(result) {
      try {
        const submission = {
          user_id: parseInt(localStorage.getItem('userId')),
          problem_id: parseInt(this.$route.params.id), // 从路由参数获取题目ID
          source_code: result.source_code,
          language_id: this.selectedLanguage,
          status: result.status,
          execution_time: result.execution_time || 0,
          memory_used: result.memory_used || 0
        };

        const response = await axios({
          method: 'post',
          url: baseURL + '/CodeQuestion-service/problems/insertSubmission',
          data: submission
        });

        if (response.data.result === 'success') {
          console.log('提交记录保存成功');
        } else {
          console.error('提交记录保存失败:', response.data.message);
        }
      } catch (error) {
        console.error('保存提交记录时发生错误:', error);
      }
    },
    // 获取提交历史记录
    async showSubmissionHistory() {
      this.showHistoryModal = true;
      this.isHistoryLoading = true;
      this.historyError = '';
      this.submissions = [];
      
      try {
        const problemId = this.$route.params.id;
        const response = await axios.get(`${baseURL}/CodeQuestion-service/problems/getSubmissionByProblemId/${problemId}`);
        
        if (response.data.result === 'success') {
          this.submissions = response.data.submissionList || [];
        } else {
          throw new Error(response.data.message || '获取提交历史失败');
        }
      } catch (error) {
        console.error('获取提交历史记录失败:', error);
        this.historyError = error.message || '获取历史记录失败，请稍后重试';
      } finally {
        this.isHistoryLoading = false;
      }
    },
    
    // 关闭历史记录弹窗
    closeHistoryModal() {
      this.showHistoryModal = false;
    },
    
    // 显示提交详情
    showSubmissionDetail(submission) {
      this.selectedSubmission = submission;
      this.showDetailModal = true;
    },
    
    // 关闭提交详情弹窗
    closeDetailModal() {
      this.showDetailModal = false;
      this.selectedSubmission = {};
    },
    
    // 获取状态对应的CSS类
    getStatusClass(status) {
      if (!status) return '';
      
      status = status.toLowerCase();
      if (status.includes('accepted') || status === 'success') {
        return 'success';
      } else if (status.includes('error') || status.includes('wrong')) {
        return 'error';
      } else {
        return 'pending';
      }
    },
    
    // 获取语言名称
    getLanguageName(languageId) {
      if (!languageId) return '未知语言';
      
      const language = this.languages.find(lang => lang.id === languageId);
      return language ? language.name : '未知语言';
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-';
      
      try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      } catch (e) {
        return dateString;
      }
    },
    // 解析Judge0错误信息，使其更友好
    formatJudge0Error(status, stderr, compileOutput) {
      if (!status) return '未知错误';
      
      let message = `错误类型: ${status.description || '未知'}`;
      
      // 根据状态ID提供更具体的信息
      switch (status.id) {
        case 6: // 编译错误
          message = '编译错误: 代码无法编译，请检查语法';
          break;
        case 7: // 超时
          message = '运行超时: 代码执行时间过长';
          break;
        case 8: // 内存溢出
          message = '内存溢出: 代码使用内存过多';
          break;
        case 9: // 运行时错误
          message = '运行时错误: 代码执行时出现异常';
          break;
        case 10: // 系统错误
          message = '系统错误: 评测系统出现问题，请稍后再试';
          break;
        case 11: // 编译器错误
          message = '编译器错误: 评测系统编译器出现问题，请稍后再试';
          break;
        // 可以添加更多具体的状态处理
      }
      
      // 添加更详细的错误信息
      let details = [];
      
      // 添加编译输出
      if (compileOutput && compileOutput.trim()) {
        let cleanCompileOutput = compileOutput
          .replace(/\/tmp\/[a-zA-Z0-9_.\/]+:/g, '') // 移除临时文件路径
          .replace(/main\.[a-z]+:/g, '') // 移除main.c:等前缀
          .trim();
        
        // 确保编译错误信息可读性
        if (status.id === 6) { // 编译错误
          details.push(`编译错误详情:\n${cleanCompileOutput}`);
          
          // 添加针对典型错误的建议
          if (cleanCompileOutput.includes('printf')) {
            details.push("提示: 检查printf函数的格式字符串是否正确，确保%d等占位符数量与提供的变量数量一致。");
          }
          if (cleanCompileOutput.includes('undeclared')) {
            details.push("提示: 检查变量是否在使用前已声明。");
          }
          if (cleanCompileOutput.includes('expected')) {
            details.push("提示: 语法错误，检查是否缺少分号、括号或存在多余字符。");
          }
        } else {
          details.push(`编译输出:\n${cleanCompileOutput}`);
        }
      }
      
      // 添加运行时错误
      if (stderr && stderr.trim()) {
        let cleanStderr = stderr
          .replace(/\/tmp\/[a-zA-Z0-9_.\/]+:/g, '') // 移除临时文件路径
          .trim();
        details.push(`标准错误输出:\n${cleanStderr}`);
        
        // 对于特定错误添加提示
        if (stderr.includes('segmentation fault')) {
          details.push("提示: 代码可能存在内存访问错误，检查数组越界或指针使用。");
        }
        if (stderr.includes('floating point exception')) {
          details.push("提示: 可能存在除以零或其他非法数学运算。");
        }
      }
      
      // 组合所有信息
      if (details.length > 0) {
        message += '\n\n' + details.join('\n\n');
      }
      
      // 针对两数之和题目添加特别提示
      if (this.problem && this.problem.title && this.problem.title.includes('两数之和')) {
        message += '\n\n对于两数之和问题的特别提示: 确保代码只输出计算结果（如"3"），不要添加额外文字（如"两数之和为: 3"）。';
      }
      
      return message;
    },
    
    // 添加拖拽相关方法
    startResize(event) {
      this.isResizing = true;
      this.initialHeight = document.querySelector('.run-result').offsetHeight;
      this.initialMouseY = event.clientY;
      
      // 添加事件监听
      document.addEventListener('mousemove', this.doResize);
      document.addEventListener('mouseup', this.stopResize);
      
      // 防止文本选择
      document.body.style.userSelect = 'none';
    },
    
    doResize(event) {
      if (!this.isResizing) return;
      
      const deltaY = this.initialMouseY - event.clientY;
      const newHeight = this.initialHeight + deltaY;
      
      // 设置最小高度和最大高度
      if (newHeight < 100) return;  // 最小高度
      const maxHeight = document.querySelector('.code-editor').offsetHeight * 0.7;  // 最大高度为编辑器区域的70%
      if (newHeight > maxHeight) return;
      
      this.resultHeight = newHeight;
      
      // 直接调整结果区域的高度
      const resultElement = document.querySelector('.run-result');
      if (resultElement) {
        resultElement.style.height = `${this.resultHeight}px`;
      }
      
      // 调整CodeMirror编辑器高度
      this.adjustEditorHeight();
    },
    
    stopResize() {
      this.isResizing = false;
      
      // 移除事件监听
      document.removeEventListener('mousemove', this.doResize);
      document.removeEventListener('mouseup', this.stopResize);
      
      // 恢复文本选择
      document.body.style.userSelect = '';
    },
    
    adjustEditorHeight() {
      if (this.editor && this.showResult) {
        // 调整编辑器高度，考虑结果区域的高度
        const editorContainer = document.querySelector('.code-editor');
        const editorHeaderHeight = document.querySelector('.editor-header').offsetHeight;
        const testcaseTipHeight = document.querySelector('.testcase-tip').offsetHeight;
        const availableHeight = editorContainer.offsetHeight - editorHeaderHeight - testcaseTipHeight - this.resultHeight - 30; // 30是边距
        
        this.editor.setSize(null, availableHeight);
      }
    }
  },
  watch: {
    selectedLanguage(newLang) {
      if (this.editor) {
        // 直接调用changeLanguage方法来更新编辑器语言模式
        this.changeLanguage()
      }
    },
    
    // 添加监听结果显示状态的变化
    showResult(newVal) {
      if (newVal) {
        // 如果显示结果，调整编辑器高度
        this.$nextTick(() => {
          this.adjustEditorHeight();
        });
      } else {
        // 如果隐藏结果，恢复编辑器高度
        this.$nextTick(() => {
          this.editor.setSize(null, '100%');
        });
      }
    }
  }
}
</script>

<style scoped>
.problem-detail {
  display: flex;
  height: 100vh;
  background: #f0f2f5;
  overflow: hidden;
  position: relative;
  padding: 20px;
  gap: 20px;
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 8px 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #4a5568;
  transition: all 0.2s;
  z-index: 100;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.back-button:hover {
  background: #f8fafd;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

/* 通用面板样式 */
.panel {
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  background: white;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

/* 左侧题目区域样式 */
.problem-info {
  width: 400px;
  margin-top: 60px; /* 为返回按钮留出空间 */
  overflow-y: auto;
  padding: 24px;
}

.problem-header {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #edf2f7;
}

.problem-header .problem-title {
  margin: 0 0 16px 0;
  font-size: 24px;
  color: #1a202c;
  font-weight: 700;
  letter-spacing: -0.5px;
  line-height: 1.3;
  text-shadow: 0 1px 2px rgba(0,0,0,0.05);
  transition: color 0.3s ease;
}

.problem-header .problem-title:hover {
  color: #3182ce;
}

.problem-meta {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.meta-item {
  color: #718096;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.example-item {
  background: #f8fafd;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.example-item h3 {
  color: #4a5568;
  margin-bottom: 12px;
  font-size: 16px;
}

.example-box {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 8px;
  font-family: 'Fira Code', monospace;
}

/* 中间编辑器区域样式 */
.code-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 60px; /* 为返回按钮留出空间 */
  background: white;
  overflow: hidden; /* 确保内容不溢出 */
  position: relative;
}

/* 当显示结果时，调整布局 */
.code-editor.has-result {
  display: grid;
  grid-template-rows: auto 1fr auto;
}

.code-editor.has-result .run-result {
  flex: 1;
  min-height: 200px;
  max-height: 45%;
}

.editor-header {
  padding: 12px 16px;
  background: #f8fafd;
  border-bottom: 1px solid #e2e8f0;
  border-radius: 12px 12px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.language-select {
  width: 200px;
}

.language-select select {
  width: 100%;
  background: white;
  color: #4a5568;
  border: 1px solid #e2e8f0;
  padding: 8px 12px;
  border-radius: 6px;
  outline: none;
  font-size: 14px;
  appearance: auto;
  cursor: pointer;
}

.editor-actions {
  display: flex;
  gap: 12px;
}

.run-btn, .submit-btn {
  padding: 10px 24px;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  font-size: 15px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: 42px;
  min-width: 110px;
}

.run-btn {
  background: #4299e1;
  color: white;
}

.run-btn:hover {
  background: #3182ce;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 153, 225, 0.3);
}

.submit-btn {
  background: #48bb78;
  color: white;
}

.submit-btn:hover {
  background: #38a169;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(72, 187, 120, 0.3);
}

.run-btn:disabled, .submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

/* 运行结果区域样式优化 */
.run-result {
  margin-top: 16px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  overflow: hidden;
  transition: height 0.2s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  height: 200px; /* 默认高度 */
  position: relative; /* 为resize-handle定位 */
}

/* 添加拖拽把手样式 */
.resize-handle {
  width: 100%;
  height: 8px;
  background: #f8fafd;
  position: absolute;
  bottom: 0;
  left: 0;
  cursor: ns-resize; /* 南北方向调整光标 */
  border-top: 1px solid #e2e8f0;
}

.resize-handle::after {
  content: '';
  position: absolute;
  top: 3px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 2px;
  background: #cbd5e0;
  border-radius: 1px;
}

.resize-handle:hover::after {
  background: #a0aec0;
}

/* 调整结果内容样式 */
.result-content {
  flex: 1;
  overflow-y: auto;
  font-family: 'Fira Code', monospace;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
  padding: 16px 20px;
  padding-bottom: 24px; /* 为resize-handle留出空间 */
}

.result-content pre {
  margin: 0;
}

.result-content.success {
  background-color: #f0fff4;
  color: #276749;
  border-left: 4px solid #48bb78;
}

.result-content.error {
  background-color: #fff5f5;
  color: #c53030;
  border-left: 4px solid #f56565;
}

.result-content.loading {
  background-color: #ebf8ff;
  color: #2c5282;
  position: relative;
  border-left: 4px solid #4299e1;
}

.result-content.loading:after {
  content: '';
  position: absolute;
  height: 3px;
  background: linear-gradient(90deg, transparent, #4299e1, transparent);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  top: 0;
  left: 0;
  right: 0;
}

@keyframes loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* 右侧 AI 助手样式 */
.ai-assistant {
  width: 320px;
  margin-top: 60px; /* 为返回按钮留出空间 */
  transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  will-change: width, transform;
}

.ai-assistant.collapsed {
  width: 60px;
}

.ai-header {
  padding: 16px;
  background: #f8fafd;
  border-bottom: 1px solid #e2e8f0;
  border-radius: 12px 12px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-header h2 {
  font-size: 16px;
  color: #2d3748;
  margin: 0;
  white-space: nowrap;
  opacity: 1;
  transition: opacity 0.3s ease;
}

.ai-assistant.collapsed .ai-header h2 {
  opacity: 0;
  position: absolute;
  left: -9999px;
}

.collapse-btn {
  background: none;
  border: none;
  color: #718096;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  width: 28px;
  height: 28px;
  transition: all 0.3s ease;
  z-index: 2;
}

.collapse-btn:hover {
  background: #edf2f7;
  color: #3182ce;
}

.ai-content {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 140px);
  transition: opacity 0.4s ease, transform 0.4s ease;
  opacity: 1;
  transform: translateX(0);
}

.ai-assistant.collapsed .ai-content {
  opacity: 0;
  transform: translateX(30px);
  pointer-events: none;
}

.quick-actions {
  padding: 12px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  background: #f8fafd;
}

.action-btn {
  padding: 8px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 13px;
  transition: all 0.2s;
}

.action-btn.hint {
  color: #d69e2e;
}

.action-btn.approach {
  color: #3182ce;
}

.action-btn.complexity {
  color: #805ad5;
}

.action-btn.optimize {
  color: #38a169;
}

.action-btn:hover {
  background: #f8fafd;
  transform: translateY(-1px);
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #fff;
}

.chat-message {
  margin-bottom: 12px;
  padding: 10px 14px;
  border-radius: 12px;
  max-width: 95%;
  width: fit-content;
  position: relative;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
  transition: all 0.3s ease;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.chat-message.user {
  background: #ebf8ff;
  margin-left: auto;
  color: #2c5282;
  border-bottom-right-radius: 4px;
}

.chat-message.ai {
  background: #f7fafc;
  color: #2d3748;
  margin-right: auto;
  border-bottom-left-radius: 4px;
  position: relative;
}

.chat-message.ai.error {
  background: #fff5f5;
  color: #c53030;
  border-left: 3px solid #fc8181;
}

.message-content {
  position: relative;
  word-break: break-word;
  line-height: 1.6;
}

.message-content .ai-avatar {
  position: absolute;
  top: -30px;
  left: -10px;
  background: #4299e1;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

/* AI正在输入的动画效果 - 改进版 */
.chat-message.ai.is-loading {
  padding-bottom: 24px; /* 为加载动画留出空间 */
}

.chat-message.ai.is-loading:after {
  content: '';
  position: absolute;
  bottom: 8px;
  left: 14px; /* 与消息内容对齐 */
  width: 40px;
  height: 8px;
  background: #e2e8f0;
  border-radius: 4px;
  overflow: hidden;
}

.chat-message.ai.is-loading:before {
  content: '';
  position: absolute;
  bottom: 8px;
  left: 14px;
  width: 40px;
  height: 8px;
  background: linear-gradient(90deg, 
    transparent, 
    transparent 25%, 
    #4299e1 25%, 
    #4299e1 50%, 
    transparent 50%, 
    transparent 75%, 
    #4299e1 75%);
  background-size: 20px 20px;
  border-radius: 4px;
  z-index: 1;
  animation: typing 1.2s infinite linear;
}

@keyframes typing {
  0% { transform: translateX(-20px); }
  100% { transform: translateX(20px); }
}

/* Markdown格式样式 */
.chat-message.ai .message-content {
  font-size: 14px;
}

/* Markdown内容样式 */
.message-content h1, 
.message-content h2, 
.message-content h3, 
.message-content h4, 
.message-content h5, 
.message-content h6 {
  margin-top: 16px;
  margin-bottom: 10px;
  font-weight: 600;
  line-height: 1.4;
  color: #2d3748;
}

.message-content h1 { font-size: 1.6em; }
.message-content h2 { font-size: 1.5em; }
.message-content h3 { font-size: 1.3em; }
.message-content h4 { font-size: 1.2em; }
.message-content h5 { font-size: 1.1em; }
.message-content h6 { font-size: 1em; }

.message-content p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.message-content strong {
  font-weight: 600;
  color: #2c5282;
}

.message-content em {
  font-style: italic;
  color: #4a5568;
}

.message-content ul, 
.message-content ol {
  margin: 8px 0 12px 20px;
  padding-left: 20px;
}

.message-content li {
  margin-bottom: 4px;
}

.message-content ol {
  list-style-type: decimal;
}

.message-content ul {
  list-style-type: disc;
}

.message-content blockquote {
  padding: 10px 15px;
  margin: 10px 0;
  border-left: 4px solid #e2e8f0;
  background: #f7fafc;
  color: #4a5568;
}

.message-content a {
  color: #3182ce;
  text-decoration: none;
  word-break: break-all;
}

.message-content a:hover {
  text-decoration: underline;
}

.message-content code {
  background: #edf2f7;
  padding: 3px 6px;
  border-radius: 4px;
  font-family: 'Fira Code', Monaco, 'Courier New', monospace;
  font-size: 0.9em;
  color: #805ad5;
}

.message-content pre {
  background: #2d3748;
  color: #e2e8f0;
  padding: 12px 16px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 12px 0;
}

.message-content pre code {
  background: transparent;
  color: #e2e8f0;
  padding: 0;
  border-radius: 0;
  font-size: 0.9em;
  line-height: 1.5;
}

.message-content table {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
}

.message-content table th,
.message-content table td {
  border: 1px solid #e2e8f0;
  padding: 6px 10px;
  text-align: left;
}

.message-content table th {
  background-color: #f7fafc;
  font-weight: 600;
}

.message-content hr {
  border: none;
  border-top: 1px solid #e2e8f0;
  margin: 16px 0;
}

.message-content img {
  max-width: 100%;
  border-radius: 4px;
  margin: 8px 0;
}

/* 发送按钮禁用状态 */
.send-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 聊天输入框 */
.chat-input {
  padding: 12px;
  background: #f8fafd;
  border-top: 1px solid #e8f4ff;
  display: flex;
  gap: 8px;
}

.chat-input input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  outline: none;
  transition: border-color 0.2s;
}

.chat-input input:focus {
  border-color: #4299e1;
}

.send-btn {
  padding: 8px 16px;
  background: #4299e1;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.2s;
}

.send-btn:hover {
  background: #3182ce;
}

/* 难度标签样式 */
.difficulty-tag {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
}

.difficulty-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.12);
}

.difficulty-tag i {
  font-size: 10px;
}

.difficulty-tag .easy-icon {
  color: #38b2ac;
}

.difficulty-tag .medium-icon {
  color: #ecc94b;
}

.difficulty-tag .hard-icon {
  color: #e53e3e;
}

.difficulty-tag.easy {
  background: linear-gradient(135deg, #e6fffa, #b2f5ea);
  color: #234e52;
  border: 1px solid #81e6d9;
}

.difficulty-tag.medium {
  background: linear-gradient(135deg, #fffff0, #fefcbf);
  color: #744210;
  border: 1px solid #f6e05e;
}

.difficulty-tag.hard {
  background: linear-gradient(135deg, #fff5f5, #fed7d7);
  color: #822727;
  border: 1px solid #fc8181;
}

/* 题目内容样式优化 */
.problem-content {
  font-size: 15px;
  line-height: 1.7;
  color: #4a5568;
  margin-bottom: 24px;
}

.problem-content p {
  margin-bottom: 16px;
}

.problem-content strong {
  color: #2d3748;
  font-weight: 600;
}

.problem-content code {
  background: #f7fafc;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Fira Code', monospace;
  font-size: 0.9em;
  color: #805ad5;
  border: 1px solid #edf2f7;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f7fafc;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e0;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a0aec0;
}

/* CodeMirror 自定义样式 */
:deep(.CodeMirror) {
  height: 100%;
  font-family: 'Fira Code', monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #2d3748;
  background: #fafafa;
  border: 1px solid #e2e8f0;
  border-radius: 0 0 8px 8px;
}

:deep(.CodeMirror-gutters) {
  border-right: 1px solid #e2e8f0;
  background-color: #f8fafd;
}

:deep(.CodeMirror-linenumber) {
  color: #a0aec0;
}

:deep(.CodeMirror-cursor) {
  border-left: 2px solid #4299e1;
}

:deep(.CodeMirror-selected) {
  background: #ebf8ff !important;
}

:deep(.CodeMirror-line) {
  padding: 0 8px;
}

/* 代码编辑器容器调整，确保结果区域可见 */
:deep(.CodeMirror-wrap) {
  margin-bottom: 10px;
}

/* 当存在运行结果时，调整布局 */
.has-result :deep(.CodeMirror) {
  height: auto !important;
}

/* 当没有结果时，编辑器占满可用空间 */
.code-editor:not(.has-result) :deep(.CodeMirror) {
  height: calc(100vh - 150px) !important;
}

/* 提交历史弹窗样式 */
.submission-history-modal, .submission-detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-container {
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  width: 80%;
  max-width: 800px;
  position: relative;
  z-index: 1000;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.submission-detail-modal .modal-container {
  max-width: 900px;
}

/* 提交历史按钮样式 */
.history-btn {
  padding: 6px 12px;
  background: linear-gradient(135deg, #ebf8ff, #bee3f8);
  color: #2c5282;
  border: 1px solid #bee3f8;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
}

.history-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.12);
  background: linear-gradient(135deg, #e6fffa, #b2f5ea);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-header h3 {
  font-size: 18px;
  font-weight: 600;
}

.close-modal-btn {
  background: none;
  border: none;
  color: #718096;
  cursor: pointer;
  font-size: 18px;
}

.modal-body {
  padding: 16px;
  overflow-y: auto;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.history-error {
  color: #c53030;
  text-align: center;
  padding: 16px;
}

.no-history {
  text-align: center;
  padding: 16px;
}

.submission-table-container {
  max-height: 300px;
  overflow-y: auto;
}

.submission-table {
  width: 100%;
  border-collapse: collapse;
}

.submission-table th,
.submission-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e2e8f0;
}

.submission-table th {
  background-color: #f7fafc;
}

.submission-table tbody tr {
  cursor: pointer;
  transition: all 0.2s ease;
}

.submission-table tbody tr:hover {
  background-color: #f8fafd;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.submission-info {
  margin-bottom: 16px;
}

.info-row {
  margin-bottom: 8px;
}

.label {
  font-weight: 600;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 600;
}

.success {
  background-color: #f0fff4;
  color: #276749;
}

.error {
  background-color: #fff5f5;
  color: #c53030;
}

.pending {
  background-color: #ebf8ff;
  color: #2c5282;
}

.submission-code {
  margin-top: 24px;
  border-top: 1px solid #e2e8f0;
  padding-top: 16px;
}

.submission-code h4 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
}

.submission-code pre {
  background: #2d3748;
  color: #e2e8f0;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  max-height: 400px;
  overflow-y: auto;
}

.submission-code pre code {
  background: transparent;
  color: #e2e8f0;
  padding: 0;
  border-radius: 0;
  font-size: 0.9em;
  line-height: 1.5;
}

/* 测试用例提示区域样式 */
.testcase-tip {
  display: flex;
  padding: 12px 16px;
  background: #ebf8ff;
  border-left: 4px solid #4299e1;
  border-radius: 0 6px 6px 0;
  margin: 0 0 16px 0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.tip-icon {
  font-size: 18px;
  color: #3182ce;
  margin-right: 12px;
  padding-top: 2px;
}

.tip-content {
  flex: 1;
  font-size: 14px;
  color: #2c5282;
}

.tip-content p {
  margin: 0 0 8px 0;
  line-height: 1.5;
}

.tip-content strong {
  color: #2a4365;
  font-weight: 600;
}

.tip-content ul {
  margin: 8px 0;
  padding-left: 20px;
}

.tip-content li {
  margin-bottom: 4px;
  list-style-type: disc;
}

/* ... existing code ... */

.test-case-format-info {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  margin-bottom: 16px;
  background-color: #e6f7ff;
  border-radius: 8px;
  border-left: 4px solid #1890ff;
}

.test-case-format-info i {
  font-size: 18px;
  color: #1890ff;
  margin-right: 12px;
}

.test-case-format-info p {
  margin: 0;
  color: #333;
  font-size: 14px;
}

.test-case-format-info strong {
  font-weight: 600;
}

/* ... existing code ... */
</style> 